package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.demo.DBServer.SqlInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:application-targetdatasource.properties")
@MapperScan(basePackages = TargetMyBatisConfig.PACKAGES, sqlSessionFactoryRef = "targetSqlSessionFactory")
public class TargetMyBatisConfig {

    static final String PACKAGES = "com.example.demo.DBServer.targetDatabase";


    @ConfigurationProperties(prefix = "spring.target.datasource")
    @Bean(name = "targetDataSource")
    public DataSource targetDataSource(){
        return new DruidDataSource();
    }

    @Bean(name = "targetTransactionManager")
    public DataSourceTransactionManager targetTransactionManager(@Qualifier("targetDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "targetConfiguration")
    @ConfigurationProperties(prefix = "mybatis.target.configuration")
    public org.apache.ibatis.session.Configuration globalConfiguration() {
        return new org.apache.ibatis.session.Configuration();
    }

    @Bean(name = "targetSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("targetDataSource") DataSource dataSource,
                                                     @Qualifier("targetConfiguration") org.apache.ibatis.session.Configuration config) throws Exception {
        config.addInterceptor(new SqlInterceptor());
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setConfiguration(config);
        return sessionFactoryBean.getObject();
    }

}
